#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> // close()
#include <arpa/inet.h> // inet_pton()
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 8080
#define BUFF_SIZE 1024

int main(){
    //创建socket
    int socket_id = socket(AF_INET,SOCK_STREAM, 0);
    if(socket_id < 0){
        perror("socket");
        return -1;
    }

    //设置服务器地址
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);

    //将字符串形式的IP地址转换为二进制形式
    int res = inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
    if(res < 0){
        perror("inet_pton");
        return -1;
    }

    res = connect(socket_id, (struct sockaddr *)&server_addr, sizeof(server_addr));

    if(res < 0){
        perror("connect");
        return -1;
    }

    printf("connect server success!\n");
    //缓存要发送的信息
    char buffer[BUFF_SIZE];
    while(1){
        memset(buffer, 0, sizeof(buffer));
        printf("please input:");
        //从stdin中获取输入写入buffer
        fgets(buffer, BUFF_SIZE-1, stdin);
       
        //判断是否退出
        if(!strncmp(buffer,"quit",4)){
            break;
        }
        //发送数据
        int send_len = send(socket_id, buffer, strlen(buffer), 0);
        if(send_len <0){
            perror("send");
            break;
        }

        if(send_len == 0){
            printf("server close the connection\n");
            break;
        }
        char recv_buffer[BUFF_SIZE]={0};
        int recv_len = recv(socket_id, recv_buffer, BUFF_SIZE-1, 0);
        if(recv_len <0){
            perror("recv");
            break;
        }

        if(recv_len == 0){
            printf("server close the connection\n");
            break;
        }

        printf("server say: %s\n", recv_buffer);
    }
   
    //关闭文件描述符，关闭连接
    close(socket_id);
    return 0;
}